package com.rajesh.messageservice.crack;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.rajesh.messageservice.bean.ImageFlag;
import com.rajesh.messageservice.bean.UserInfo;
import com.rajesh.messageservice.helper.GlobalConfig;
import com.rajesh.messageservice.helper.JsonHttpClient;
import com.rajesh.messageservice.helper.QueryStrings;

import java.util.List;

/**
 * 上传/更新用户头像
 */
public class HeadImgService extends Service {
    public static final String ACTION = "com.rajes.messageservice.crack.HeadImgService";

    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                HeadImgService.syncHeadImages(HeadImgService.this);
            }
        }).start();
        return super.onStartCommand(intent, START_FLAG_RETRY, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    public static void syncHeadImages(Context context) {
        try {
            DatabaseCracker cracker = DatabaseCracker.createInstance(context);
            JsonHttpClient jsonHttpClient = new JsonHttpClient();

            List<ImageFlag> imageFlags = cracker.select(ImageFlag.class, QueryStrings.QUERY_ALL_HEADIMG);
            ImageFlag selfImageFlag = cracker.single(ImageFlag.class, QueryStrings.QUERY_SELF_HEADIMG);
            UserInfo userInfo = cracker.single(UserInfo.class, QueryStrings.QUERY_CURRENT_USER_INFO);
            selfImageFlag.setUserName(userInfo.getUserName());

            if (imageFlags != null) {
                imageFlags.add(selfImageFlag);
                jsonHttpClient.post(GlobalConfig.UploadImgFlagUrl, imageFlags);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
